const path = require('path');
const fs = require('fs');
// import fs from 'fs';

function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split('&');
  searchArr.forEach(v => {
    const index = v.indexOf('=');
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/* 自动注入controller下的全部mock */
function injectMocks() {
  const files = require.context('./controller', false, /\.js$/);
  const mocks = files.keys().reduce((modules, key) => {
    modules.push(...files(key).default);
    return modules;
  }, []);
  return mocks;
}

/* 在webpack初始化之前，require.context不能使用，context是webpack的方法 */
function injectServerMocks() {
  const mockDir = path.resolve(__dirname, 'controller');
  // const mockDir = 'mock/controller';
  const files = fs.readdirSync(mockDir);
  const mocks = files.reduce((all, _path) => {
    const filePath = path.join(mockDir, _path).replace(/\\/g, '/');
    const stat = fs.statSync(filePath);
    if (stat.isFile() && /\.js$/.test(filePath)) {
      const mock = require(`./controller/${_path}`).default;
      all.push(...mock);
    }
    return all;
  }, []);
  return mocks;
}

module.exports = {
  injectMocks,
  injectServerMocks,
  param2Obj,
};
